package com.rongzhe.house.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.rongzhe.house.manager.PositionManager;

/**
 * Created by huang on 2018/1/20.
 */

public class LocationService extends Service {
    private static  final int LOCATION_TIMEOUT = 5 * 1000;
    public LocationClient mLocationClient = null;
    @Override
    public void onCreate() {
        super.onCreate();
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(mBdLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setTimeOut(5 * 1000);
        mLocationClient.setLocOption(option);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PositionManager.getInstance().setBDLocation(null);
            stop();
        }
    };

    private void stop() {
        mLocationClient.unRegisterLocationListener(mBdLocationListener);
        mLocationClient.stop();
        stopSelf();
    }

    private BDAbstractLocationListener mBdLocationListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location){
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                PositionManager.getInstance().setBDLocation(location);
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                PositionManager.getInstance().setBDLocation(location);
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                PositionManager.getInstance().setBDLocation(location);
            } else {
                //定位失败
                PositionManager.getInstance().setBDLocation(null);
            }
            stop();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
            mHandler.sendEmptyMessageDelayed(1, LOCATION_TIMEOUT);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
